package bit.project.controller;

import bit.project.common.AppResult;
import bit.project.common.ResultCode;
import bit.project.model.User;
import bit.project.services.IUserService;
import bit.project.utils.MD5Utils;
import bit.project.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Api(tags = "用户接口")
@Slf4j //日志
@RestController//返回具体数据控制器
@RequestMapping("/user")//一级映射路径
public class UserController {
    @Resource
    private IUserService iUserService;
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register (@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                               @ApiParam("昵称") @RequestParam("nickname")@NonNull String nickname,
                               @ApiParam("密码") @RequestParam("password")@NonNull String password,
                               @ApiParam("确认密码") @RequestParam("passwordRepeat")@NonNull String passwordRepeat){
        //判断密码与密码是否相同
        if(!password.equals(passwordRepeat)){
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //判断用户是否存在
        User existuser = iUserService.selectByUserName(username);
        if(existuser!=null){
            return AppResult.failed(ResultCode.FAILED_USER_EXISTS);
        }
        //生成盐
        String salt  = UUIDUtils.UUID_32();
        //生成密文
        String ciphertext = MD5Utils.md5salt(password,salt);
        //构造User对象
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        user.setPassword(password);
        user.setSalt(salt);
        //调用service
        iUserService.createNormalUser(user);

          return AppResult.success();
    }
}
